/* eslint-disable react-hooks/exhaustive-deps */
import React, { useState, useEffect } from 'react';
import { useBoolean, useRequest } from 'ahooks';
import { Tabs, Button, Form, Input, Modal, Space, Table, Upload, message, Select, Spin, Image, Cascader } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { If } from 'babel-plugin-jsx-control-statements';
import Cookies from 'js-cookie';
import RequestApi from '@/utils/request';
import css from './index.scss';

// 信息已完善组件
const FinishedInfo = () => {
	const userId = Cookies.get('id');
	const [completeData, setCompleteData] = useState();
	const [userDistrictList, setUserDistrictList] = useState();
	useEffect(() => {
		RequestApi.connection('get', `userExtendMsg/getUserOrg/${userId}`).then((res) => {
			setCompleteData(res.data);
		});
	}, []);
	// 获取停车区域信息
	useEffect(() => {
		RequestApi.connection('get', `userDistrict/getUserDistrictList/${userId}`).then((res) => {
			setUserDistrictList(res.data.rows);
		});
	}, []);
	// 用户停车区域的列表
	const userDistrictNameList = [];
	if (userDistrictList !== undefined && userDistrictList !== null) {
		userDistrictList.map((item) => {
			userDistrictNameList.push(item.name);
			return userDistrictNameList;
		});
	}
	// console.log('userDistrictList: ', userDistrictList);
	// 下拉停车区域的级联信息菜单
	const [options, setOptions] = useState();
	useEffect(() => {
		RequestApi.connection('get', `district/getList`).then((res) => {
			setOptions(res.data);
		});
	}, []);
	const optionsNameList = [];
	if (options !== undefined) {
		options.map((item) => {
			optionsNameList.push(item.name);
			return null;
		});
	}
	// 更新停车区域
	async function updateDistrict(districtIds) {
		// 排出特殊情况防止请求出错
		// console.log('districtIds: ', districtIds);
		const newUserId = Number(userId);
		RequestApi.connection('post', `userDistrict/updateDistrict/${newUserId}`, districtIds).then(() => {
			message.success('停车区域修改成功');
		});
		return new Promise((resolve) => {
			setTimeout(() => {
				resolve(districtIds);
			}, 300);
		});
	}
	const { loading, run } = useRequest(updateDistrict, {
		debounceInterval: 3000,
		manual: true,
	});
	return (
		<>
			<div className={css.finishedInfoContent}>
				<div className={css.welcomeInfo}>
					<h2 style={{ color: 'white', fontSize: 30 }}>
						<strong>欢迎</strong>
					</h2>
					<h4>
						经营者
						{userId}
					</h4>
				</div>
				<div className={css.detailInfo}>
					<p>单位名称营业执照绑定后不可修改,若需要更换单位和营业执照,请重新注册账号再绑定停车场</p>
				</div>
				<If
					condition={
						completeData !== undefined &&
						completeData !== null &&
						userDistrictList !== undefined &&
						userDistrictList !== null
					}
				>
					<div className={css.perfectedInfo}>
						<div>
							单位名称：
							{completeData.row.orgName}
						</div>
						<div>
							单位地址：
							{completeData.row.orgAddress}
						</div>
						<div>
							营业执照：
							<Image src={completeData.row.filePath} />
						</div>
						<If condition={options !== null && options !== undefined}>
							<div>
								停车场所在区域:
								<Select
									mode="multiple"
									allowClear
									style={{ width: '200%' }}
									placeholder="Please select"
									defaultValue={userDistrictNameList}
									onChange={(e) => run(e)}
									// onBlur={updateDistrict}
								>
									{loading
										? null
										: options.map((item) => (
												<Select.Option value={item.id} key={item.id}>
													{item.name}
												</Select.Option>
										  ))}
								</Select>
							</div>
						</If>
					</div>
				</If>
			</div>
		</>
	);
};

// 信息未完善组件
const UnfinishedInfo = () => {
	const userId = Cookies.get('id');
	const [completeData, setCompleteData] = useState();
	const [userDistrictList, setUserDistrictList] = useState();
	const [form] = Form.useForm();
	const [isModalVisible, setIsModalVisible] = useState(false);
	// 完善信息窗口展示
	const showModal = () => {
		setIsModalVisible(true);
	};
	// 获取所有单位列表
	const [companyOptions, setCompanyOptions] = useState();
	useEffect(() => {
		RequestApi.connection('post', `orgnization/getOrgList`).then((res) => {
			setCompanyOptions(res.data);
		});
	}, []);

	// 文件上传按钮
	const uploadFile = {
		headers: {
			authorization: 'authorization-text',
		},
		beforeUpload: () => {
			return false;
		},
		onChange(info) {
			if (info.file.status === 'done') {
				message.success(`${info.file.name} file uploaded successfully`);
			} else if (info.file.status === 'error') {
				message.error(`${info.file.name} file upload failed.`);
			}
		},
	};
	const handleCancel = () => {
		setIsModalVisible(false);
	};

	// 下拉停车区域的级联信息菜单
	const [options, setOptions] = useState();
	useEffect(() => {
		RequestApi.connection('get', `district/getList`).then((res) => {
			setOptions(res.data);
		});
	}, []);
	const [isperfectInfo, setIsperfectInfo] = useState(true);
	const [btnDisplay, setBtnDisplay] = useState('block');
	const [divDisplay, setDivDisplay] = useState('none');

	const onFinish = (formValues) => {
		if (companyOptions !== undefined && companyOptions !== null) {
			companyOptions.map((item) => {
				if (item.name === formValues.orgName) {
					formValues.orgId = item.id;
				}
				return null;
			});
		}
		const newValues = {};
		newValues.userId = Number(userId);
		if (formValues !== null && formValues !== undefined) {
			newValues.orgAddress = formValues.orgAddress;
			newValues.orgId = formValues.orgId;
			newValues.orgName = formValues.orgName;
			newValues.userDistrictIds = formValues.userDistrictIds;
		}
		if (formValues.uploadFile !== null && formValues.uploadFile !== undefined) {
			const uploadFileFormData = new FormData();
			uploadFileFormData.append('file', formValues.uploadFile.file);
			// 处理文件上传
			RequestApi.connection('post', `oss/upload/${3}/${0}/${6}`, uploadFileFormData).then((response) => {
				// console.log('response', response);
				newValues.fileId = response.data.row.id;
				newValues.filePath = response.data.row.path;
				// console.log('newValues1:', newValues);
				RequestApi.connection('post', `/userExtendMsg/completeOrgMsg`, newValues)
					.then(() => {
						message.success('信息提交成功');
					})
					.catch(() => {
						message.error('信息提交失败,可能是数据未填写完！！');
					});
				setIsperfectInfo(true);
				setDivDisplay(isperfectInfo ? 'block' : 'none');
				setBtnDisplay('none');
				handleCancel();
			});
		}
	};

	// 信息已完善之后
	useEffect(() => {
		RequestApi.connection('get', `userExtendMsg/getUserOrg/${userId}`).then((res) => {
			setCompleteData(res.data);
		});
	}, []);
	// 获取停车区域信息
	useEffect(() => {
		RequestApi.connection('get', `userDistrict/getUserDistrictList/${userId}`).then((res) => {
			setUserDistrictList(res.data.rows);
		});
	}, []);
	// 用户停车区域的列表
	const userDistrictNameList = [];
	if (userDistrictList !== undefined && userDistrictList !== null) {
		userDistrictList.map((item) => {
			userDistrictNameList.push(item.name);
			return userDistrictNameList;
		});
	}

	const optionsNameList = [];
	if (options !== undefined) {
		options.map((item) => {
			optionsNameList.push(item.name);
			return null;
		});
	}

	return (
		<>
			<div className={css.leftContent}>
				<div className={css.welcomeInfo}>
					<h2 style={{ color: 'white', fontSize: 30 }}>
						<strong>欢迎</strong>
					</h2>
					<h4>
						经营者
						{userId}
					</h4>
				</div>
				<div className={css.detailInfo}>
					<p>单位名称营业执照绑定后不可修改,若需要更换单位和营业执照,请重新注册账号再绑定停车场</p>
				</div>
				<div className={css.completeInfoBtn} style={{ display: btnDisplay }}>
					<Button type="primary" shape="round" onClick={showModal}>
						完善单位信息
					</Button>
				</div>
				<Modal title="完善单位信息" visible={isModalVisible} onCancel={handleCancel} footer={[]}>
					<Form name="completeInfo" form={form} onFinish={onFinish}>
						<If condition={companyOptions !== undefined && companyOptions !== null}>
							<Form.Item
								label="单位名称："
								name="orgName"
								rules={[{ required: { isModalVisible }, message: '单位名称不能为空' }]}
							>
								<Select placeholder="请选择单位名称" filterOption={false} showSearch>
									{companyOptions.map((item) => (
										<Select.Option value={item.name} key={item.name}>
											{item.name}
										</Select.Option>
									))}
								</Select>
							</Form.Item>
						</If>
						<If condition={companyOptions !== undefined && companyOptions !== null}>
							<Form.Item
								label="单位地址："
								name="orgAddress"
								rules={[{ required: { isModalVisible }, message: '单位地址不能为空' }]}
							>
								<Input type="text" name="orgAddress" placeholder="请输入单位地址" />
							</Form.Item>
						</If>
						<Form.Item label="营业执照：" name="uploadFile" rules={[{ required: true, message: '营业执照不能为空' }]}>
							<Upload {...uploadFile}>
								<Button icon={<UploadOutlined />}>上传文件</Button>
							</Upload>
						</Form.Item>
						<Form.Item
							label="停车场所在区域"
							name="userDistrictIds"
							rules={[{ required: { isModalVisible }, message: '停车区域不能为空' }]}
						>
							<Cascader
								fieldNames={{ label: 'name', value: 'id', children: 'sonArea' }}
								options={options}
								placeholder="Please select"
							/>
						</Form.Item>
						<Space>
							<Button type="primary" htmlType="submit" style={{ marginLeft: 140 }}>
								提交
							</Button>
							<Button onClick={handleCancel}>取消</Button>
						</Space>
					</Form>
				</Modal>
			</div>
			<If condition={divDisplay === 'block'}>
				<If
					condition={
						completeData !== undefined &&
						completeData !== null &&
						userDistrictList !== undefined &&
						userDistrictList !== null
					}
				>
					<div className={css.perfectedInfo}>
						<div>
							单位名称：
							{completeData.row.orgName}
						</div>
						<div>
							单位地址：
							{completeData.row.orgAddress}
						</div>
						<div>
							营业执照：
							<Image src={completeData.row.filePath} />
						</div>
						<If condition={options !== null && options !== undefined}>
							<div>
								停车场所在区域:
								{/* <Select
									mode="multiple"
									allowClear
									style={{ width: '200%' }}
									placeholder="Please select"
									defaultValue={userDistrictNameList}
								> */}
								<Cascader
									fieldNames={{ label: 'name', value: 'id', children: 'sonArea' }}
									options={options}
									placeholder="Please select"
									defaultValue={userDistrictNameList}
								/>
								{/* </Select> */}
							</div>
						</If>
					</div>
				</If>
			</If>
		</>
	);
};

export default () => {
	const userId = Cookies.get('id');
	const { TabPane } = Tabs;
	const [flagCode, setFlagCode] = useState(); // 用于判断单位信息是否完整的标志
	const [data, setData] = useState(); // 存放表格信息
	const [loading, { setTrue, setFalse }] = useBoolean(false);
	const defaultPageSize = 20;
	const [pswForm] = Form.useForm();
	// 获取flagCode
	useEffect(() => {
		const newNewId = Number(userId);
		RequestApi.connection('get', `userExtendMsg/getUserOrg/${newNewId}`).then((res) => {
			setFlagCode(res.code);
		});
	}, []);
	// -------------- 个人中心--------密码修改---------------------
	// 修改密码提交按钮
	const pswOnFinish = (formValues) => {
		formValues.id = Number(userId);
		RequestApi.connection('post', `user/updatePassword`, formValues)
			.then((response) => {
				if (response.code === 200) {
					message.success('修改密码成功');
				}
				if (response.code === 201) {
					message.error('修改密码失败，请检查原密码是否正确');
				}
			})
			.catch(() => {
				message.error('修改密码失败！！！');
			});
	};

	// -------------- 个人中心--------消息通知---------------------
	useEffect(() => {
		setTrue();
		RequestApi.connection('get', `/announcement/getAll/${userId}/${1}/${defaultPageSize}`).then((res) => {
			setData(res.data.rows);
			setFalse();
		});
	}, []);

	const columns = [
		{
			title: '序号',
			render: (text, record, index) => `${index + 1}`,
			ellipsis: true,
		},
		{
			title: '消息通知',
			dataIndex: 'content',
			ellipsis: true,
		},
		{
			title: '时间',
			dataIndex: 'createdAt',
			ellipsis: true,
		},
	];

	return (
		<>
			<Tabs className={css.allTabs} tabPosition="left">
				<TabPane tab="单位信息" key="companyInfo">
					<If condition={flagCode === 200}>
						<FinishedInfo />
					</If>
					<If condition={flagCode === 201}>
						<UnfinishedInfo />
					</If>
				</TabPane>
				<TabPane tab="修改密码" key="changePsg">
					<Form name="changePsd" labelCol={{ span: 5 }} form={pswForm} onFinish={pswOnFinish}>
						<Form.Item
							label="原密码（必填）  "
							name="oldPassword"
							rules={[
								{
									required: true,
									message: '输入密码不能为空',
								},
							]}
						>
							<Input.Password style={{ width: 450 }} />
						</Form.Item>

						<Form.Item
							label="新密码（必填）  "
							name="newPassword"
							rules={[
								{
									required: true,
									message: '输入密码不能为空',
								},
							]}
						>
							<Input.Password style={{ width: 450 }} />
						</Form.Item>

						<Form.Item
							label="确认密码（必填）"
							name="confirmPassword"
							rules={[
								({ getFieldValue }) => ({
									validator(rule, value) {
										if (!value || getFieldValue('newPassword') === value) {
											return Promise.resolve();
										}
										return Promise.reject('该密码与新密码输入不一致');
									},
								}),
								{
									required: true,
									message: '输入密码不能为空',
								},
							]}
						>
							<Input.Password style={{ width: 450 }} />
						</Form.Item>

						<Form.Item
							wrapperCol={{
								offset: 5,
								span: 16,
							}}
						>
							<Button type="primary" htmlType="submit">
								保存
							</Button>
						</Form.Item>
					</Form>
				</TabPane>

				<TabPane tab="消息通知" key="msgNotify">
					<Spin spinning={loading} tip="加载中...">
						<Table
							size="small"
							bordered
							columns={columns}
							scroll={{ x: 1000, y: 'calc(100vh - 290px)' }}
							dataSource={data}
						/>
					</Spin>
				</TabPane>
			</Tabs>
		</>
	);
};
